package com.ttx.zookeeper.crud;

import com.ttx.zookeeper.DefaultWatcher;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.ZooDefs;
import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.data.Stat;

import java.io.IOException;

/**
 * crud节点
 *
 * @author TimFruit
 * @date 20-2-27 下午6:52
 */
public class RawSample {

    public static void main(String[] args) throws IOException, KeeperException, InterruptedException {
        String connectString="127.0.0.1:2181";

        ZooKeeper zk=new ZooKeeper(connectString, 10*1000, new DefaultWatcher());


        String testPath="/my_test21";

        // create
        if(zk.exists(testPath, false)==null){
            zk.create(testPath, "my_data".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
        }



        // get
        Stat stat=new Stat();
        byte[] data=zk.getData(testPath,false, stat);
        System.out.println("version: "+stat.getVersion());
        System.out.println(new String(data));



        // set
        zk.setData(testPath, "new_data".getBytes(), stat.getVersion());


        // get
        stat=new Stat();
        data=zk.getData(testPath,false, stat);
        System.out.println("version: "+stat.getVersion());
        System.out.println(new String(data));


        // delete
        zk.delete(testPath, stat.getVersion());




        // close
        zk.close();

    }


}
